using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MediPlatform.Infeartructure;

namespace MediPlatform.Read.Api.Controllers
{
    /// <summary>
    /// 测试控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class TestController : ControllerBase
    {
        private readonly MyDbContext _context;
        private readonly ILogger<TestController> _logger;

        public TestController(MyDbContext context, ILogger<TestController> logger)
        {
            _context = context;
            _logger = logger;
        }

        /// <summary>
        /// 测试数据库连接
        /// </summary>
        /// <returns>连接状态</returns>
        [HttpGet("database")]
        public async Task<IActionResult> TestDatabaseConnection()
        {
            try
            {
                var canConnect = await _context.Database.CanConnectAsync();
                return Ok(new 
                { 
                    Success = canConnect, 
                    Message = canConnect ? "数据库连接成功" : "数据库连接失败",
                    Timestamp = DateTime.UtcNow
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "数据库连接测试失败");
                return StatusCode(500, new 
                { 
                    Success = false, 
                    Message = "数据库连接测试失败",
                    Error = ex.Message,
                    Timestamp = DateTime.UtcNow
                });
            }
        }

        /// <summary>
        /// 测试用户数量
        /// </summary>
        /// <returns>用户数量</returns>
        [HttpGet("users-count")]
        public async Task<IActionResult> GetUsersCount()
        {
            try
            {
                var count = await _context.User.CountAsync();
                return Ok(new 
                { 
                    Count = count,
                    Message = $"当前共有 {count} 个用户",
                    Timestamp = DateTime.UtcNow
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户数量失败");
                return StatusCode(500, new 
                { 
                    Error = "获取用户数量失败",
                    Message = ex.Message,
                    Timestamp = DateTime.UtcNow
                });
            }
        }

        /// <summary>
        /// 测试认证（需要登录）
        /// </summary>
        /// <returns>认证信息</returns>
        [HttpGet("auth")]
        [Authorize]
        public IActionResult TestAuth()
        {
            var username = User.FindFirst(System.Security.Claims.ClaimTypes.Name)?.Value;
            var role = User.FindFirst(System.Security.Claims.ClaimTypes.Role)?.Value;
            var userId = User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;

            return Ok(new
            {
                Message = "认证成功",
                Username = username,
                Role = role,
                UserId = userId,
                Timestamp = DateTime.UtcNow
            });
        }

        /// <summary>
        /// 测试管理员权限
        /// </summary>
        /// <returns>管理员权限验证</returns>
        [HttpGet("admin")]
        [Authorize(Roles = "admin")]
        public IActionResult TestAdminAuth()
        {
            var username = User.FindFirst(System.Security.Claims.ClaimTypes.Name)?.Value;

            return Ok(new
            {
                Message = "管理员权限验证成功",
                Username = username,
                Role = "admin",
                Timestamp = DateTime.UtcNow
            });
        }

        /// <summary>
        /// 测试医生权限
        /// </summary>
        /// <returns>医生权限验证</returns>
        [HttpGet("doctor")]
        [Authorize(Roles = "doctor")]
        public IActionResult TestDoctorAuth()
        {
            var username = User.FindFirst(System.Security.Claims.ClaimTypes.Name)?.Value;

            return Ok(new
            {
                Message = "医生权限验证成功",
                Username = username,
                Role = "doctor",
                Timestamp = DateTime.UtcNow
            });
        }

        /// <summary>
        /// 测试患者权限
        /// </summary>
        /// <returns>患者权限验证</returns>
        [HttpGet("patient")]
        [Authorize(Roles = "patient")]
        public IActionResult TestPatientAuth()
        {
            var username = User.FindFirst(System.Security.Claims.ClaimTypes.Name)?.Value;

            return Ok(new
            {
                Message = "患者权限验证成功",
                Username = username,
                Role = "patient",
                Timestamp = DateTime.UtcNow
            });
        }
    }
} 